import React from 'react';
import {inject, observer} from 'mobx-react';
import {toJS, observable, autorun} from 'mobx';
import {WeaTable, WeaTableEditable, WeaTools, WeaDialog, WeaSearchGroup, WeaInput, WeaFormItem, 
    WeaDropdown, WeaSelect, WeaDatePicker, WeaTransfer, WeaCheckbox, WeaBrowser, WeaOrgTree, WeaLocaleProvider} from 'ecCom';
import {Button, Row, Menu, Switch, Input, message} from "antd";

import './style/';

const getLabel = WeaLocaleProvider.getLabel;

@inject("PerformanceElementSettingStore", "StringUtilsStore")
@observer
class Setting extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: getLabel(508544, "标题"),
                    dataIndex: 'title',
                    key: 'title',
                    com: [
                        {
                            type: 'INPUT', 
                            viewAttr: 1, 
                            key: 'title', 
                            width: 120 
                        }
                    ]
                },
                {
                    title: getLabel(30585, "操作"),
                    dataIndex: 'operation',
                    key: 'operation',
                    com: [
                        {
                            type: 'CUSTOM', 
                            viewAttr: 1, 
                            key: 'operation', 
                            width: 120, 
                            render: (text, record, index, onEdit) => {
                                return (
                                    <span>
                                        <span id={`common-click-set-${index}`} className="common-click-workrelate" onClick={this.handleSetSpanClick}>{getLabel(30747, "设置")}</span>
                                        &nbsp;&nbsp;
                                        <span id={`common-click-othersave-${index}`} className="common-click-workrelate" onClick={this.handleOtherSaveSpanClick}>{getLabel(506965, "另存为")}</span>
                                    </span> 
                                )
                            }
                      }
                    ]
                }
            ],
            tableDatas: []
        };
        // 将当前组件实例传递到元素组件，以便元素组件获取到该组件
        props.getInstance && props.getInstance(this);
    }

    componentWillMount () {
        // 获取元素设置数据
        const {params = {}, PerformanceElementSettingStore, StringUtilsStore} = this.props;
        //const {eid} = params;

        WeaTools.callApi("/api/workrelate/performance/accessAssessmentCycle", "GET", {}).then((result) => {
            let options = []
            if (result && result.stabList) {
                result.stabList.sort((a, b) => {
                    return a.viewcondition - b.viewcondition
                }).forEach((d, i) => {
                    options.push({
                        key: "2-" + d.key,
                        showname: d.title
                    })
                })
            }
            options = options.length> 0 ? options : [{key: "", showname: ""}]
            PerformanceElementSettingStore.changePerformanceDateRangeValues2Options(options)

            WeaTools.callApi('/api/workrelate/portal/element/getSettingData', 'GET', {eid:params.eid}).then((result) => {
                if (result) {
                    let tableDatas = [];
                    for (let k in result) {
                        const {tabseq, title, selectedBigType, orderby, showCount, performanceDateRangeValue1, performanceDateRangeValue2,
                            performanceDateRangeValue3, selectedPerformanceStatus, selectedPerformanceType, performancePersonsStr,
                            selectedSubDepOption, performanceSubDepStr, selectedDepOption, performanceDepStr} = result[k]
                        tableDatas.push({
                            id: tabseq,
                            title,
                            selectedBigType,
                            orderby,
                            showCount,
                            performanceDateRangeValue1,
                            performanceDateRangeValue2,
                            performanceDateRangeValue3,
                            selectedPerformanceStatus,
                            selectedPerformanceType,
                            performancePersonsStr,
                            selectedSubDepOption,
                            performanceSubDepStr,
                            selectedDepOption,
                            performanceDepStr
                        })
                    }
    
                    // 设置默认数据
                    // if (tableDatas.length == 0) {
                    //     let defaultTableDatas = toJS(PerformanceElementSettingStore.defaultTableDatas)
                    //     if (Array.isArray(defaultTableDatas)) {
                    //         defaultTableDatas.forEach((d, i) => {
                    //             d.performanceDateRangeValue2 = PerformanceElementSettingStore.performanceDateRangeValues2Options[0].key
                    //             tableDatas.push(d)
                    //         })
                    //     }
                    // }
    
                    this.setState({
                        tableDatas
                    })
                }
            });
        })
    }

    handleSetSpanClick = (e) => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.selectedTableDataId = e.target.id.substring(e.target.id.lastIndexOf("-") + 1)
        PerformanceElementSettingStore.contentSettingDialogVisibleMethod = "set"
        PerformanceElementSettingStore.changeContentSettingDialogVisible(true)
        PerformanceElementSettingStore.setContentSettingDialog(this.state.tableDatas[parseInt(PerformanceElementSettingStore.selectedTableDataId)])
    }

    handleOtherSaveSpanClick = (e) => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.selectedTableDataId = e.target.id.substring(e.target.id.lastIndexOf("-") + 1)
        PerformanceElementSettingStore.contentSettingDialogVisibleMethod = "othersave"
        PerformanceElementSettingStore.changeContentSettingDialogVisible(true)
        PerformanceElementSettingStore.setContentSettingDialog(this.state.tableDatas[parseInt(PerformanceElementSettingStore.selectedTableDataId)])
    }

    onDialogSureClick = () => {
        const {PerformanceElementSettingStore, StringUtilsStore} = this.props
        if (!StringUtilsStore.allIsNotEmpty(PerformanceElementSettingStore.tabTitle, 
            PerformanceElementSettingStore.selectedBigType, PerformanceElementSettingStore.performanceDateRangeValue2)) {
            message.warning(getLabel(15859 , "必要信息不完整！"))
            return
        }

        PerformanceElementSettingStore.changeContentSettingDialogVisible(false)

        let currTableData = {
            //id: PerformanceElementSettingStore.tableDatas.length,
            title: PerformanceElementSettingStore.tabTitle,
            selectedBigType: PerformanceElementSettingStore.selectedBigType,
            orderby: PerformanceElementSettingStore.orderby,
            showCount: PerformanceElementSettingStore.showCount,
            performanceDateRangeValue1: PerformanceElementSettingStore.performanceDateRangeValue1,
            performanceDateRangeValue2: PerformanceElementSettingStore.performanceDateRangeValue2,
            performanceDateRangeValue3: PerformanceElementSettingStore.performanceDateRangeValue3,
            selectedPerformanceStatus: PerformanceElementSettingStore.showPerformanceStatusSetting ? PerformanceElementSettingStore.selectedPerformanceStatus : "",
            selectedPerformanceType: PerformanceElementSettingStore.showPerformanceTypeSetting ? PerformanceElementSettingStore.selectedPerformanceType : "",
            performancePersonsStr: PerformanceElementSettingStore.showPerformancePersonsSetting ? PerformanceElementSettingStore.performancePersonsStr : "",
            selectedSubDepOption: PerformanceElementSettingStore.showPerformanceSubDepSetting ? PerformanceElementSettingStore.selectedSubDepOption : "",
            performanceSubDepStr: PerformanceElementSettingStore.showPerformanceSubDepSetting ? PerformanceElementSettingStore.performanceSubDepStr : "",
            selectedDepOption: PerformanceElementSettingStore.showPerformanceDepSetting ? PerformanceElementSettingStore.selectedDepOption : "",
            performanceDepStr: PerformanceElementSettingStore.showPerformanceDepSetting ?  PerformanceElementSettingStore.performanceDepStr : ""
        }

        if (PerformanceElementSettingStore.contentSettingDialogVisibleMethod == "add" || PerformanceElementSettingStore.contentSettingDialogVisibleMethod == "othersave") {
            this.state.tableDatas.push(Object.assign({id: this.state.tableDatas.length}, currTableData))
        } else if (PerformanceElementSettingStore.contentSettingDialogVisibleMethod == "set") {
            let selectedTableDataId = parseInt(PerformanceElementSettingStore.selectedTableDataId)
            this.state.tableDatas[selectedTableDataId] = Object.assign({id: selectedTableDataId}, currTableData)
        } 
        this.setState({
            tableDatas: this.state.tableDatas
        })
    }

    onDialogCancleClick = () => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.changeContentSettingDialogVisible(false)
    }

    onAddBtnClick = () => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.contentSettingDialogVisibleMethod = "add"
        PerformanceElementSettingStore.changeContentSettingDialogVisible(true)
        PerformanceElementSettingStore.setDefaultContentSettingDialog()
    }

    onDelBtnClick = (datas, keys) => {
        const {PerformanceElementSettingStore} = this.props

        keys.sort((a, b) => {
            return b - a
        }).forEach((d, i) => {
            this.state.tableDatas.splice(d, 1)
        })

        // 重新设置数据主键
        this.state.tableDatas.map((item, index) => {
            item.id = index;
        })

        this.setState({
            tableDatas: this.state.tableDatas
        })
    }

    onGroupbyIconClick = () => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.initOrderbyTransferDatas()
        PerformanceElementSettingStore.changeOrderbyTransferDialogVisible(true)
    }

    onDataSequenceChange = (datas, other) => {
        const {PerformanceElementSettingStore} = this.props
        datas.map((item, index) => {
            item.id = index;
        })

        this.setState({
            tableDatas: datas
        })
    }

    onOrderbyTransferDialogSureClick = () => {
        const {PerformanceElementSettingStore} = this.props
        let orderby = ""

        PerformanceElementSettingStore.orderbyTransferSelectedKeys.forEach((d, i) => {
            PerformanceElementSettingStore.orderbyTransferDatas.forEach((dd, ii) => {
                if (d == dd.id) {
                    orderby += (dd.name + "-" + dd.orderType + ",")
                }
            })
        })

        if (orderby != "") {
            orderby = orderby.substring(0, orderby.length - 1)
        }

        PerformanceElementSettingStore.changeOrderby(orderby)
        PerformanceElementSettingStore.changeOrderbyTransferDialogVisible(false)
    }

    onOrderbyTransferDialogCancleClick = () => {
        const {PerformanceElementSettingStore} = this.props
        PerformanceElementSettingStore.changeOrderbyTransferDialogVisible(false)
        PerformanceElementSettingStore.initOrderbyTransferDatas()
    }

    render () {
        const {columns} = this.state
        const {PerformanceElementSettingStore, StringUtilsStore} = this.props

        // dialog内容的设置
        let dialogContent = (
            <div>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@q96av5`} title = {getLabel(82751, "基础设置")} showGroup = {true}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@r99oh1`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@b8qeuu`}
                            style = {{marginLeft: 30}}
                            label={getLabel(508544, "标题")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@wwv5z6`} 
                                        viewAttr={3}
                                        value={PerformanceElementSettingStore.tabTitle} 
                                        onChange={(value) => {
                                            PerformanceElementSettingStore.changeTabTitle(value)
                                        }}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@30su53`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@79sqvo`}
                            style = {{marginLeft: 30}}
                            label={getLabel(15512, "排序字段")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{paddingTop: "7px"}}>
                                <i className="icon-coms-Flow-setting icon-coms-Flow-setting-hover-workrelate" 
                                   onClick={this.onGroupbyIconClick}
                                />
                                <span style={{paddingLeft: "6px"}}>{PerformanceElementSettingStore.orderby}</span>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@05420k`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@l4t9y3`}
                            style = {{marginLeft: 30}}
                            label={getLabel(128851, "显示总数")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{paddingTop: "6px"}}>
                                <Switch ecId={`${this && this.props && this.props.ecId || ''}_Switch@j1eevp`} 
                                    size={"small"}
                                    checked={PerformanceElementSettingStore.showCount == "1"} 
                                    onChange={(value) => {
                                        PerformanceElementSettingStore.showCount = value ? "1" : "0"
                                    }}
                                />
                            </div>
                        </WeaFormItem>
                    </Row>
                </WeaSearchGroup>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@jtr3fr`} title = {getLabel(127253, "来源设置")} showGroup = {true}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8z0oq5`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@g08rv2`}
                            style = {{marginLeft: 30}}
                            label={getLabel(16850, '类别')}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@7mritk`} 
                                        options = {PerformanceElementSettingStore.bigTypeOptions}
                                        viewAttr={3}
                                        value = {PerformanceElementSettingStore.selectedBigType}
                                        onChange = {(v) => {PerformanceElementSettingStore.selectedBigType = v}}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@qfto3n`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@p6n24n`}
                            style = {{marginLeft: 30}}
                            label={getLabel(15386, '周期')}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{position: "relative", width: "100%"}}>
                                <div style = {{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@sbzg2w`} 
                                        viewAttr={3}
                                        options = {PerformanceElementSettingStore.performanceDateRangeValues2Options}
                                        value = {PerformanceElementSettingStore.performanceDateRangeValue2}
                                        onChange = {(value) => {
                                            PerformanceElementSettingStore.changePerformanceDateRangeValue2(value)
                                            PerformanceElementSettingStore.changePerformanceDateRangeValue3("")
                                        }}
                                    />
                                </div>
                            </div>
                        </WeaFormItem>
                    </Row>
                    {PerformanceElementSettingStore.showPerformanceStatusSetting ? 
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ato3fq`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@mhvkwe`}
                            style = {{marginLeft: 30}}
                            label={getLabel(23247, "状态")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@mfdq7v`} 
                                    multiple
                                    options={PerformanceElementSettingStore.performanceStatusOptions}
                                    viewAttr={2}
                                    value = {PerformanceElementSettingStore.selectedPerformanceStatus}
                                    onChange={(v) => {PerformanceElementSettingStore.changeSelectedPerformanceStatus(v)}}
                                >
                                </WeaSelect> 
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    }
                    {PerformanceElementSettingStore.showPerformanceTypeSetting ?
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zzjxjp`}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4las2q`}
                            style = {{marginLeft: 30}}
                            label={getLabel(500401, "类型")}
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <div style={{width: "90%", height: "100%", display: "inline-block", verticalAlign: "middle"}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@xfeght`} 
                                    options={PerformanceElementSettingStore.performanceTypeOptions}
                                    viewAttr={2}
                                    value = {PerformanceElementSettingStore.selectedPerformanceType}
                                    onChange={(v) => {PerformanceElementSettingStore.changeSelectedPerformanceType(v)}}
                                >
                                </WeaSelect> 
                            </div>
                        </WeaFormItem>
                    </Row>
                    : ""
                    }
                </WeaSearchGroup>
            </div>
        )

        // 排序Dialog内容的设置
        let orderbyTransferDialogContent = (
            <div style={{width: "600px", margin: "0 auto"}}>
                <WeaTransfer ecId={`${this && this.props && this.props.ecId || ''}_WeaTransfer@jspjjh`} 
                    data = {PerformanceElementSettingStore.orderbyTransferDatas}
                    height = {300}
                    selectedKeys = {
                        PerformanceElementSettingStore.orderbyTransferSelectedKeys
                    }
                    onChange = {(keys, datas) => {
                        let orderbyTransferDatas = toJS(PerformanceElementSettingStore.orderbyTransferDatas)

                        orderbyTransferDatas.forEach((d, i) => {
                            if (keys.join(",").indexOf(d.id + "") == -1) {
                                d.orderType = "";
                            } else {
                                if (d.orderType == "") {
                                    d.orderType = getLabel(384984, "降序")
                                }
                            }
                        })
                        PerformanceElementSettingStore.changeOrderbyTransferDatas(orderbyTransferDatas)
                        PerformanceElementSettingStore.changeOrderbyTransferSelectedKeys(keys)
                    }}
                    renderItem = {(item) => {
                        return (
                            <div style={{height: 37, lineHeight: "37px", borderBottom: "1px solid rgb(226,226,226)", position: "relative"}}>
                                <span style={{paddingLeft: "10px", display: "inline-block"}}>{item.name}</span>
                                <span 
                                    style={{position: "absolute", top: "0px", right: "10px", display: "inline-block"}} 
                                    onClick={(e) => {
                                            e.preventDefault()
                                            e.stopPropagation()
                                            let orderbyTransferDatas = toJS(PerformanceElementSettingStore.orderbyTransferDatas)
                                            orderbyTransferDatas.forEach((d, i) => {
                                                if (d.id == item.id) {
                                                    d.orderType = (item.orderType == getLabel(384985, "升序") ? getLabel(384984, "降序") : getLabel(384985, "升序"))
                                                }
                                            })
                                            PerformanceElementSettingStore.changeOrderbyTransferDatas(orderbyTransferDatas)
                                        }
                                    }
                                >
                                    {item.orderType}
                                </span>
                            </div>
                        )
                    }}
                />
            </div>
        )

        return (
            <div className="portal-performance-element-setting">
                <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@68tujo`}
                    rowKey = {"id"}
                    datas = {this.state.tableDatas}
                    // title = {getLabel(20885, "内容来源")}
                    title = ""
                    draggable = {true}
                    columns = {columns}
                    showCopy = {false}
                    willAdd = {this.onAddBtnClick}
                    willDelete = {this.onDelBtnClick}
                    onChange = {this.onDataSequenceChange}
                />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@lvn7ba`} 
                    hasScroll = {true}
                    visible = {PerformanceElementSettingStore.contentSettingDialogVisible}
                    title = {getLabel(506919, "内容设置")}
                    buttons = {
                        [
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kh4uwv@sure`} type="primary" onClick={this.onDialogSureClick}>
                              {getLabel(826, '确定')}
                            </Button>,
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rpsh2d@cancel`} type="ghost" onClick={this.onDialogCancleClick}>
                              {getLabel(31129, '取消')}
                            </Button>
                        ]
                    }
                    onCancel = {() => {PerformanceElementSettingStore.changeContentSettingDialogVisible(false)}}
                    children = {dialogContent}
                />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zhq4bq`} 
                    style = {{width: 600, height: 300}}
                    visible = {PerformanceElementSettingStore.orderbyTransferDialogVisible}
                    title = {getLabel(386541, '排序字段设置')}
                    buttons = {
                        [
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9ftsc6@sure`} type="primary" onClick={this.onOrderbyTransferDialogSureClick}>
                              {getLabel(826, '确定')}
                            </Button>,
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h1f47u@cancel`} type="ghost" onClick={this.onOrderbyTransferDialogCancleClick}>
                              {getLabel(31129, '取消')}
                            </Button>
                        ]
                    }
                    onCancel = {this.onOrderbyTransferDialogCancleClick}
                    children = {orderbyTransferDialogContent}
                />
            </div>
        );
    }

    onSave = () => {
        // 保存元素设置数据
        // 如果有必填项，校验不通过时，需要return false;
        const {params = {}, PerformanceElementSettingStore} = this.props;
        //const {eid} = params;
        const {tableDatas} = this.state
        WeaTools.callApi('/api/workrelate/portal/element/saveSettingData', 'POST', {
            tableDatas: JSON.stringify(toJS(tableDatas)),
            eid:params.eid
        });
    }
}

export default Setting;
